from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.core.files.storage import default_storage
from django.conf import settings
from django.contrib.auth import authenticate
from django.utils import timezone
from .models import Employee
import json
import os
import uuid
from datetime import datetime
from PIL import Image
import logging

# 配置日志记录器
logger = logging.getLogger(__name__)

# 登录API
@csrf_exempt
@require_http_methods(["POST"])
def user_login(request):
    """
    用户登录API - 使用用户名和密码登录
    
    Args:
        request: HTTP请求对象，包含用户名和密码
    
    Returns:
        JsonResponse: 包含登录结果的JSON响应
    """
    try:
        data = json.loads(request.body.decode('utf-8'))
        username = data.get('username', '').strip()
        password = data.get('password', '')
        
        if not username or not password:
            return JsonResponse({
                'status': 'error',
                'message': '用户名和密码不能为空'
            }, status=400)
        
        # 查找用户
        try:
            user = Employee.objects.get(username=username)
            
            # 检查用户状态
            if user.status != '启用':
                logger.warning(f"用户已被禁用: {username}")
                return JsonResponse({
                    'status': 'error',
                    'message': '该账号已被禁用，请联系管理员'
                }, status=401)
            
            # 验证密码
            if user.check_password(password):
                # 更新最后登录时间（仅管理员）
                if user.is_admin:
                    user.last_login_time = timezone.now()
                    user.save(update_fields=['last_login_time'])
                
                # 准备用户信息
                user_data = {
                    'id': str(user.id),
                    'username': user.username,
                    'name': user.name,
                    'role': 'admin' if user.is_admin else ('safety' if user.is_safety_officer else 'employee'),
                    'phone': user.phone,
                    'email': user.email,
                    'avatar': f'/media/{user.avatar}' if user.avatar else '',
                    'department': user.department,
                    'position': user.position,
                    'status': 'active' if user.status == '启用' else 'inactive'
                }
                
                # 根据角色添加权限信息
                if user.is_admin:
                    user_data['permissions'] = user.permissions if user.permissions else {
                        'userManagement': True,
                        'evaluation': True,
                        'hazardTracking': True,
                        'reportManagement': True,
                        'knowledgeBase': True
                    }
                    user_data['lastLoginTime'] = user.last_login_time.strftime('%Y-%m-%d %H:%M:%S') if user.last_login_time else ''
                elif user.is_safety_officer:
                    user_data['safetyNumber'] = user.safety_number
                    user_data['licenseNumber'] = user.license_number
                    user_data['managementScope'] = user.management_scope
                elif user.is_employee:
                    user_data['employeeNumber'] = user.employee_number
                    user_data['evaluation'] = user.evaluation
                
                logger.info(f"用户登录成功: {username} ({user.get_role_display()})")
                
                return JsonResponse({
                    'status': 'success',
                    'message': '登录成功',
                    'data': user_data
                })
            else:
                logger.warning(f"密码错误: {username}")
                return JsonResponse({
                    'status': 'error',
                    'message': '用户名或密码错误'
                }, status=401)
                
        except Employee.DoesNotExist:
            logger.warning(f"用户不存在: {username}")
            return JsonResponse({
                'status': 'error',
                'message': '用户名或密码错误'
            }, status=401)
        
    except json.JSONDecodeError:
        return JsonResponse({
            'status': 'error',
            'message': '请求数据格式错误'
        }, status=400)
    except Exception as e:
        logger.error(f"登录失败: {str(e)}", exc_info=True)
        return JsonResponse({
            'status': 'error',
            'message': f'登录失败：{str(e)}'
        }, status=500)

# 登出API
@csrf_exempt
@require_http_methods(["POST"])
def user_logout(request):
    """
    用户登出API
    
    Returns:
        JsonResponse: 包含登出结果的JSON响应
    """
    try:
        logger.info("用户登出")
        return JsonResponse({
            'status': 'success',
            'message': '登出成功'
        })
    except Exception as e:
        logger.error(f"登出失败: {str(e)}", exc_info=True)
        return JsonResponse({
            'status': 'error',
            'message': f'登出失败：{str(e)}'
        }, status=500)

# API视图函数
@csrf_exempt  
@require_http_methods(["GET"])
def get_users_statistics(request):
    """获取用户统计信息"""
    try:
        # 分别统计各类型用户
        administrators_count = Employee.objects.filter(is_admin=True, status='启用').count()
        employees_count = Employee.objects.filter(is_employee=True, is_admin=False, is_safety_officer=False, status='启用').count()
        safety_officers_count = Employee.objects.filter(is_safety_officer=True, status='启用').count()
        total_users = Employee.objects.filter(status='启用').count()
        
        stats = {
            'administrators_count': administrators_count,
            'employees_count': employees_count,
            'safety_officers_count': safety_officers_count,
            'total_users': total_users
        }
        
        logger.info(f"用户统计: {stats}")
        
        return JsonResponse({
            'status': 'success',
            'data': stats
        })
    except Exception as e:
        logger.error(f"获取用户统计失败: {str(e)}", exc_info=True)
        return JsonResponse({
            'status': 'error',
            'message': f'获取用户统计失败：{str(e)}'
        }, status=500)

@csrf_exempt
@require_http_methods(["GET"])
def get_all_users(request):
    """获取所有用户列表"""
    try:
        user_type = request.GET.get('type', 'all')
        logger.info(f"获取用户列表，类型: {user_type}")
        
        data = {}
        
        if user_type in ['all', 'admin']:
            try:
                administrators = Employee.objects.filter(is_admin=True)
                admin_data = []
                for admin in administrators:
                    admin_data.append({
                        'id': str(admin.id),
                        'username': admin.username or '',
                        'name': admin.name or '',
                        'phone': admin.phone or '',
                        'email': admin.email or '',
                        'lastLoginTime': admin.last_login_time.strftime('%Y-%m-%d %H:%M') if admin.last_login_time else '从未登录',
                        'status': 'active' if admin.status == '启用' else 'inactive',
                        'remarks': admin.remarks or ''
                    })
                data['administrators'] = admin_data
                logger.info(f"成功获取 {len(admin_data)} 个管理员")
            except Exception as e:
                logger.error(f"获取管理员列表失败: {str(e)}", exc_info=True)
                data['administrators'] = []
        
        if user_type in ['all', 'employee']:
            try:
                employees = Employee.objects.filter(is_employee=True, is_admin=False, is_safety_officer=False)
                employee_data = []
                for emp in employees:
                    employee_data.append({
                        'id': str(emp.id),
                        'employeeNumber': emp.employee_number or '',
                        'name': emp.name or '',
                        'gender': emp.gender or '',
                        'department': emp.department or '',
                        'position': emp.position or '',
                        'contact': emp.contact or emp.phone or '',
                        'hireDate': emp.hire_date.strftime('%Y-%m-%d') if emp.hire_date else '',
                        'totalTasks': emp.total_tasks,
                        'completedTasks': emp.completed_tasks,
                        'completionRate': emp.completion_rate,
                        'evaluation': emp.evaluation or '待评价',
                        'status': emp.status
                    })
                data['employees'] = employee_data
                logger.info(f"成功获取 {len(employee_data)} 个普通员工")
            except Exception as e:
                logger.error(f"获取员工列表失败: {str(e)}", exc_info=True)
                data['employees'] = []
        
        if user_type in ['all', 'safety']:
            try:
                safety_officers = Employee.objects.filter(is_safety_officer=True)
                safety_data = []
                for officer in safety_officers:
                    safety_data.append({
                        'id': str(officer.id),
                        'safetyNumber': officer.safety_number or '',
                        'name': officer.name or '',
                        'gender': officer.gender or '',
                        'department': officer.department or '',
                        'position': officer.position or '',
                        'contact': officer.contact or officer.phone or '',
                        'licenseNumber': officer.license_number or '',
                        'managementScope': officer.management_scope or '',
                        'inspectionTasks': officer.inspection_tasks,
                        'lastInspectionDate': officer.last_inspection_date.strftime('%Y-%m-%d') if officer.last_inspection_date else '',
                        'status': officer.status
                    })
                data['safetyOfficers'] = safety_data
                logger.info(f"成功获取 {len(safety_data)} 个安全员")
            except Exception as e:
                logger.error(f"获取安全员列表失败: {str(e)}", exc_info=True)
                data['safetyOfficers'] = []
        
        return JsonResponse({
            'status': 'success',
            'data': data
        })
        
    except Exception as e:
        logger.error(f"获取用户列表失败: {str(e)}", exc_info=True)
        return JsonResponse({
            'status': 'error',
            'message': f'获取用户列表失败：{str(e)}'
        }, status=500)

@csrf_exempt
@require_http_methods(["POST"])
def create_user(request):
    """创建用户"""
    try:
        data = json.loads(request.body)
        user_type = data.get('type')
        
        if not user_type:
            return JsonResponse({
                'status': 'error',
                'message': '用户类型不能为空'
            }, status=400)
        
        if user_type == 'admin':
            # 验证必需字段（仅用户名必填）
            if not data.get('username'):
                return JsonResponse({
                    'status': 'error',
                    'message': '用户名不能为空'
                }, status=400)
            
            # 检查用户名是否已存在
            if Employee.objects.filter(username=data.get('username')).exists():
                return JsonResponse({
                    'status': 'error',
                    'message': '用户名已存在'
                }, status=400)
            
            # 创建管理员
            admin = Employee(
                username=data.get('username'),
                name=data.get('name', data.get('username')),  # 如果没有姓名，使用用户名
                phone=data.get('phone', ''),
                email=data.get('email', ''),
                remarks=data.get('remarks', ''),
                is_admin=True,
                is_safety_officer=False,
                is_employee=False,
                status='启用'
            )
            # 设置密码（会自动加密）
            admin.set_password(data.get('password', 'admin123'))
            admin.save()
            return JsonResponse({
                'status': 'success',
                'message': '管理员创建成功',
                'data': {
                    'id': str(admin.id),
                    'username': admin.username,
                    'name': admin.name
                }
            })
            
        elif user_type == 'employee':
            # 验证必需字段（仅用户名和密码）
            if not data.get('username') or not data.get('password'):
                return JsonResponse({
                    'status': 'error',
                    'message': '用户名和密码不能为空'
                }, status=400)
            
            username = data.get('username')
            
            # 检查用户名是否已存在
            if Employee.objects.filter(username=username).exists():
                return JsonResponse({
                    'status': 'error',
                    'message': '用户名已存在，请更换'
                }, status=400)
            
            # 字段名映射 (camelCase -> snake_case)
            hire_date_str = data.get('hireDate') or data.get('hire_date')
            hire_date = None
            if hire_date_str:
                try:
                    hire_date = datetime.strptime(hire_date_str, '%Y-%m-%d').date()
                except ValueError:
                    # 如果格式错误但不是必填，可以选择忽略或报错。这里选择忽略并设为None，或者保持原样。
                    # 为了最小化信息，允许不填。
                    pass
            
            # 创建员工
            employee = Employee(
                username=username,
                name=data.get('name', username), # 默认使用用户名
                gender=data.get('gender', ''),
                department=data.get('department', ''),
                position=data.get('position', ''),
                contact=data.get('contact', ''),
                phone=data.get('phone', data.get('contact', '')),
                hire_date=hire_date,
                is_admin=False,
                is_safety_officer=False,
                is_employee=True,
                status='启用'
            )
            # 设置密码（必填）
            employee.set_password(data.get('password'))
            employee.save()
            
            return JsonResponse({
                'status': 'success',
                'message': '员工创建成功',
                'data': {
                    'id': str(employee.id),
                    'employeeNumber': employee.employee_number,
                    'name': employee.name,
                    'username': employee.username
                }
            })
            
        elif user_type == 'safety':
            # 验证必需字段（仅用户名和密码）
            if not data.get('username') or not data.get('password'):
                return JsonResponse({
                    'status': 'error',
                    'message': '用户名和密码不能为空'
                }, status=400)
            
            username = data.get('username')
            
            # 检查用户名是否已存在
            if Employee.objects.filter(username=username).exists():
                return JsonResponse({
                    'status': 'error',
                    'message': '用户名已存在，请更换'
                }, status=400)
            
            # 字段名映射 (camelCase -> snake_case)
            hire_date_str = data.get('hireDate') or data.get('hire_date')
            license_number = data.get('licenseNumber') or data.get('license_number') or ''
            management_scope = data.get('managementScope') or data.get('management_scope') or ''
            
            hire_date = None
            if hire_date_str:
                try:
                    hire_date = datetime.strptime(hire_date_str, '%Y-%m-%d').date()
                except ValueError:
                    pass
            
            # 创建安全员
            officer = Employee(
                username=username,
                name=data.get('name', username), # 默认使用用户名
                gender=data.get('gender', ''),
                department=data.get('department', ''),
                position=data.get('position', ''),
                contact=data.get('contact', ''),
                phone=data.get('phone', data.get('contact', '')),
                hire_date=hire_date,
                license_number=license_number,
                management_scope=management_scope,
                is_admin=False,
                is_safety_officer=True,
                is_employee=False,
                status='启用'
            )
            # 设置密码（必填）
            officer.set_password(data.get('password'))
            officer.save()
            
            return JsonResponse({
                'status': 'success',
                'message': '安全员创建成功',
                'data': {
                    'id': str(officer.id),
                    'safetyNumber': officer.safety_number,
                    'name': officer.name,
                    'username': officer.username
                }
            })
        else:
            return JsonResponse({
                'status': 'error',
                'message': '无效的用户类型，支持的类型：admin, employee, safety'
            }, status=400)
            
    except json.JSONDecodeError:
        return JsonResponse({
            'status': 'error',
            'message': '请求数据格式错误'
        }, status=400)
    except Exception as e:
        logger.error(f"创建用户失败: {str(e)}", exc_info=True)
        return JsonResponse({
            'status': 'error',
            'message': f'创建用户失败：{str(e)}'
        }, status=500)

@csrf_exempt
@require_http_methods(["PUT", "PATCH"])
def update_user(request, user_id):
    """更新用户"""
    try:
        data = json.loads(request.body)
        user_type = data.get('type')
        
        if not user_type:
            return JsonResponse({
                'status': 'error',
                'message': '用户类型不能为空'
            }, status=400)
        
        # 获取用户
        try:
            user = Employee.objects.get(id=user_id)
        except Employee.DoesNotExist:
            return JsonResponse({
                'status': 'error',
                'message': '用户不存在'
            }, status=404)
        
        # 更新通用字段
        if 'name' in data:
            user.name = data['name']
        if 'gender' in data:
            user.gender = data['gender']
        if 'department' in data:
            user.department = data['department']
        if 'position' in data:
            user.position = data['position']
        if 'remarks' in data:
            user.remarks = data['remarks']
        
        # 根据用户类型更新特定字段
        if user_type == 'admin' and user.is_admin:
            if 'phone' in data:
                user.phone = data['phone']
            if 'email' in data:
                user.email = data['email']
                
        elif user_type == 'employee' and user.is_employee:
            if 'contact' in data:
                user.contact = data['contact']
            if 'phone' in data:
                user.phone = data['phone']
            
            hire_date_str = data.get('hireDate') or data.get('hire_date')
            if hire_date_str:
                try:
                    user.hire_date = datetime.strptime(hire_date_str, '%Y-%m-%d').date()
                except ValueError:
                    return JsonResponse({
                        'status': 'error',
                        'message': '入职日期格式错误，应为YYYY-MM-DD'
                    }, status=400)
                    
        elif user_type == 'safety' and user.is_safety_officer:
            if 'contact' in data:
                user.contact = data['contact']
            if 'phone' in data:
                user.phone = data['phone']
            
            license_number = data.get('licenseNumber') or data.get('license_number')
            management_scope = data.get('managementScope') or data.get('management_scope')
            hire_date_str = data.get('hireDate') or data.get('hire_date')
            
            if license_number:
                user.license_number = license_number
            if management_scope:
                user.management_scope = management_scope
            if hire_date_str:
                try:
                    user.hire_date = datetime.strptime(hire_date_str, '%Y-%m-%d').date()
                except ValueError:
                    return JsonResponse({
                        'status': 'error',
                        'message': '入职日期格式错误，应为YYYY-MM-DD'
                    }, status=400)
        
        user.save()
        
        return JsonResponse({
            'status': 'success',
            'message': '用户更新成功'
        })
            
    except json.JSONDecodeError:
        return JsonResponse({
            'status': 'error',
            'message': '请求数据格式错误'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'message': f'更新用户失败：{str(e)}'
        }, status=500)

@csrf_exempt
@require_http_methods(["PATCH"])
def toggle_user_status(request, user_id):
    """切换用户状态"""
    try:
        data = json.loads(request.body)
        
        # 获取用户
        try:
            user = Employee.objects.get(id=user_id)
        except Employee.DoesNotExist:
            return JsonResponse({
                'status': 'error',
                'message': '用户不存在'
            }, status=404)
        
        # 切换状态
        user.status = '停用' if user.status == '启用' else '启用'
        user.save()
        
        return JsonResponse({
            'status': 'success',
            'message': f'用户状态已更新为：{user.status}',
            'new_status': 'active' if user.status == '启用' else 'inactive'
        })
            
    except json.JSONDecodeError:
        return JsonResponse({
            'status': 'error',
            'message': '请求数据格式错误'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'message': f'切换用户状态失败：{str(e)}'
        }, status=500)

@csrf_exempt
@require_http_methods(["GET"])
def get_user_detail(request, user_id):
    """获取单个用户详情"""
    try:
        user_type = request.GET.get('type')
        
        if not user_type:
            return JsonResponse({
                'status': 'error',
                'message': '用户类型参数不能为空'
            }, status=400)
        
        # 获取用户
        try:
            user = Employee.objects.get(id=user_id)
        except Employee.DoesNotExist:
            return JsonResponse({
                'status': 'error',
                'message': '用户不存在'
            }, status=404)
        
        # 基本信息
        user_data = {
            'id': str(user.id),
            'username': user.username or '',
            'name': user.name or '',
            'gender': user.gender or '',
            'phone': user.phone or '',
            'email': user.email or '',
            'department': user.department or '',
            'position': user.position or '',
            'status': user.status,
            'createdAt': user.created_at.strftime('%Y-%m-%d %H:%M'),
            'type': user_type
        }
        
        # 根据角色添加特定字段
        if user_type == 'admin' and user.is_admin:
            user_data.update({
                'lastLoginTime': user.last_login_time.strftime('%Y-%m-%d %H:%M') if user.last_login_time else '从未登录',
                'remarks': user.remarks or ''
            })
        elif user_type == 'employee' and user.is_employee:
            user_data.update({
                'employeeNumber': user.employee_number or '',
                'contact': user.contact or '',
                'hireDate': user.hire_date.strftime('%Y-%m-%d') if user.hire_date else '',
                'yearsOfService': user.years_of_service,
                'totalTasks': user.total_tasks,
                'completedTasks': user.completed_tasks,
                'completionRate': user.completion_rate,
                'evaluation': user.evaluation or '待评价'
            })
        elif user_type == 'safety' and user.is_safety_officer:
            user_data.update({
                'safetyNumber': user.safety_number or '',
                'contact': user.contact or '',
                'hireDate': user.hire_date.strftime('%Y-%m-%d') if user.hire_date else '',
                'licenseNumber': user.license_number or '',
                'managementScope': user.management_scope or '',
                'inspectionTasks': user.inspection_tasks,
                'lastInspectionDate': user.last_inspection_date.strftime('%Y-%m-%d') if user.last_inspection_date else ''
            })
        
        return JsonResponse({
            'status': 'success',
            'data': user_data
        })
            
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'message': f'获取用户详情失败：{str(e)}'
        }, status=500)

@csrf_exempt
@require_http_methods(["GET"])
def get_users_by_type(request, user_type):
    """按类型获取用户列表"""
    try:
        if user_type == 'admin':
            users = Employee.objects.filter(is_admin=True)
            data = []
            for user in users:
                data.append({
                    'id': str(user.id),
                    'username': user.username or '',
                    'name': user.name or '',
                    'phone': user.phone or '',
                    'email': user.email or '',
                    'lastLoginTime': user.last_login_time.strftime('%Y-%m-%d %H:%M') if user.last_login_time else '从未登录',
                    'status': 'active' if user.status == '启用' else 'inactive',
                    'remarks': user.remarks or ''
                })
            return JsonResponse({
                'status': 'success',
                'data': data,
                'count': len(data)
            })
            
        elif user_type == 'employee':
            users = Employee.objects.filter(is_employee=True, is_admin=False, is_safety_officer=False)
            data = []
            for user in users:
                data.append({
                    'id': str(user.id),
                    'employeeNumber': user.employee_number or '',
                    'name': user.name or '',
                    'gender': user.gender or '',
                    'department': user.department or '',
                    'position': user.position or '',
                    'contact': user.contact or user.phone or '',
                    'hireDate': user.hire_date.strftime('%Y-%m-%d') if user.hire_date else '',
                    'totalTasks': user.total_tasks,
                    'completedTasks': user.completed_tasks,
                    'completionRate': user.completion_rate,
                    'evaluation': user.evaluation or '待评价',
                    'status': user.status
                })
            return JsonResponse({
                'status': 'success',
                'data': data,
                'count': len(data)
            })
            
        elif user_type == 'safety':
            users = Employee.objects.filter(is_safety_officer=True)
            data = []
            for user in users:
                data.append({
                    'id': str(user.id),
                    'safetyNumber': user.safety_number or '',
                    'name': user.name or '',
                    'gender': user.gender or '',
                    'department': user.department or '',
                    'position': user.position or '',
                    'contact': user.contact or user.phone or '',
                    'licenseNumber': user.license_number or '',
                    'managementScope': user.management_scope or '',
                    'inspectionTasks': user.inspection_tasks,
                    'lastInspectionDate': user.last_inspection_date.strftime('%Y-%m-%d') if user.last_inspection_date else '',
                    'status': user.status
                })
            return JsonResponse({
                'status': 'success',
                'data': data,
                'count': len(data)
            })
        else:
            return JsonResponse({
                'status': 'error',
                'message': '无效的用户类型，支持的类型：admin, employee, safety'
            }, status=400)
            
    except Exception as e:
        logger.error(f"按类型获取用户列表失败: {str(e)}", exc_info=True)
        return JsonResponse({
            'status': 'error',
            'message': f'获取用户列表失败：{str(e)}'
        }, status=500)

@csrf_exempt
@require_http_methods(["DELETE"])
def delete_user(request, user_id):
    """删除用户"""
    try:
        data = json.loads(request.body)
        
        # 获取用户
        try:
            user = Employee.objects.get(id=user_id)
            username = user.username
            name = user.name
            user.delete()
            return JsonResponse({
                'status': 'success',
                'message': f'用户 {name} ({username}) 删除成功'
            })
        except Employee.DoesNotExist:
            return JsonResponse({
                'status': 'error',
                'message': '用户不存在'
            }, status=404)
            
    except json.JSONDecodeError:
        return JsonResponse({
            'status': 'error',
            'message': '请求数据格式错误'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'message': f'删除用户失败：{str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["POST"])
def upload_user_avatar(request, user_id):
    """
    上传用户头像
    
    Args:
        user_id: 用户ID
    
    Returns:
        JsonResponse: 包含上传结果的JSON响应
    """
    try:
        # 获取用户类型和上传的文件
        user_type = request.POST.get('type')
        uploaded_file = request.FILES.get('avatar')
        
        if not user_type:
            return JsonResponse({
                'status': 'error',
                'message': '用户类型不能为空'
            }, status=400)
            
        if not uploaded_file:
            return JsonResponse({
                'status': 'error',
                'message': '请选择要上传的头像文件'
            }, status=400)
        
        # 验证文件类型
        allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
        if uploaded_file.content_type not in allowed_types:
            return JsonResponse({
                'status': 'error',
                'message': '不支持的文件类型，请上传 JPG、PNG、GIF 或 WebP 格式的图片'
            }, status=400)
        
        # 验证文件大小（限制2MB）
        if uploaded_file.size > 2 * 1024 * 1024:
            return JsonResponse({
                'status': 'error',
                'message': '文件大小不能超过2MB'
            }, status=400)
        
        # 获取用户对象
        try:
            user = Employee.objects.get(id=user_id)
        except Employee.DoesNotExist:
            return JsonResponse({
                'status': 'error',
                'message': '用户不存在'
            }, status=404)
        
        # 创建头像保存目录
        avatar_dir = os.path.join(settings.MEDIA_ROOT, 'avatars', user_type)
        os.makedirs(avatar_dir, exist_ok=True)
        
        # 生成唯一文件名
        file_extension = os.path.splitext(uploaded_file.name)[1].lower()
        if not file_extension:
            file_extension = '.jpg'  # 默认扩展名
        
        unique_filename = f"{user_id}_{uuid.uuid4().hex[:8]}{file_extension}"
        file_path = os.path.join(avatar_dir, unique_filename)
        
        # 处理和保存图片
        try:
            # 打开图片并进行处理
            image = Image.open(uploaded_file)
            
            # 转换为RGB模式（如果是RGBA等其他模式）
            if image.mode in ('RGBA', 'LA', 'P'):
                background = Image.new('RGB', image.size, (255, 255, 255))
                if image.mode == 'P':
                    image = image.convert('RGBA')
                background.paste(image, mask=image.split()[-1] if image.mode == 'RGBA' else None)
                image = background
            elif image.mode != 'RGB':
                image = image.convert('RGB')
            
            # 缩放图片到合适尺寸（最大200x200）
            max_size = (200, 200)
            image.thumbnail(max_size, Image.Resampling.LANCZOS)
            
            # 保存处理后的图片
            image.save(file_path, 'JPEG', quality=85, optimize=True)
            
        except Exception as img_error:
            logger.error(f"图片处理失败: {img_error}")
            return JsonResponse({
                'status': 'error',
                'message': '图片处理失败，请确保上传的是有效的图片文件'
            }, status=400)
        
        # 更新用户头像路径
        relative_path = f"avatars/{user_type}/{unique_filename}"
        
        # 删除旧头像文件（如果存在）
        if user.avatar:
            old_avatar_path = os.path.join(settings.MEDIA_ROOT, user.avatar)
            if os.path.exists(old_avatar_path):
                try:
                    os.remove(old_avatar_path)
                except Exception as e:
                    logger.warning(f"删除旧头像失败: {e}")
        
        # 保存新头像路径到数据库
        user.avatar = relative_path
        user.save(update_fields=['avatar'])
        
        logger.info(f"用户头像上传成功: {user_type} {user_id}")
        
        return JsonResponse({
            'status': 'success',
            'message': '头像上传成功',
            'data': {
                'avatar_path': relative_path,
                'avatar_url': f'/media/{relative_path}',
                'user_id': str(user_id),
                'user_type': user_type
            }
        })
        
    except json.JSONDecodeError:
        return JsonResponse({
            'status': 'error',
            'message': '请求数据格式错误'
        }, status=400)
    except Exception as e:
        logger.error(f"上传头像失败: {str(e)}", exc_info=True)
        return JsonResponse({
            'status': 'error',
            'message': f'上传头像失败：{str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["GET", "PUT"])
def user_profile_detail(request, user_id):
    """
    获取或更新用户个人资料
    
    GET: 获取用户个人资料详情
    PUT: 更新用户个人资料
    
    Args:
        user_id: 用户ID
    
    Returns:
        JsonResponse: 包含操作结果的JSON响应
    """
    try:
        user_type = request.GET.get('type') or (json.loads(request.body.decode('utf-8')).get('type') if request.method == 'PUT' else None)
        
        if not user_type:
            return JsonResponse({
                'status': 'error',
                'message': '用户类型不能为空'
            }, status=400)
        
        # 获取用户对象
        try:
            user = Employee.objects.get(id=user_id)
        except Employee.DoesNotExist:
            return JsonResponse({
                'status': 'error',
                'message': '用户不存在'
            }, status=404)
        
        if request.method == 'GET':
            # 获取用户资料
            profile_data = {
                'id': str(user.id),
                'name': user.name or '',
                'avatar': f'/media/{user.avatar}' if user.avatar else '',
                'avatar_path': user.avatar or '',
                'bio': user.bio or '',
                'type': user_type
            }
            
            # 根据用户类型添加特定字段
            if user_type == 'admin' and user.is_admin:
                profile_data.update({
                    'username': user.username or '',
                    'phone': user.phone or '',
                    'email': user.email or '',
                    'last_login_time': user.last_login_time.strftime('%Y-%m-%d %H:%M:%S') if user.last_login_time else '',
                    'status': 'active' if user.status == '启用' else 'inactive'
                })
            elif user_type in ['employee', 'safety']:
                profile_data.update({
                    'gender': user.gender or '',
                    'department': user.department or '',
                    'position': user.position or '',
                    'contact': user.contact or user.phone or '',
                    'hire_date': user.hire_date.strftime('%Y-%m-%d') if user.hire_date else '',
                    'status': user.status
                })
                
                if user_type == 'employee' and user.is_employee:
                    profile_data.update({
                        'employee_number': user.employee_number or '',
                        'years_of_service': user.years_of_service,
                        'total_tasks': user.total_tasks,
                        'completed_tasks': user.completed_tasks,
                        'completion_rate': user.completion_rate,
                        'evaluation': user.evaluation or '待评价'
                    })
                elif user_type == 'safety' and user.is_safety_officer:
                    profile_data.update({
                        'safety_number': user.safety_number or '',
                        'license_number': user.license_number or '',
                        'management_scope': user.management_scope or '',
                        'inspection_tasks': user.inspection_tasks,
                        'last_inspection_date': user.last_inspection_date.strftime('%Y-%m-%d') if user.last_inspection_date else ''
                    })
            
            return JsonResponse({
                'status': 'success',
                'data': profile_data
            })
            
        elif request.method == 'PUT':
            # 更新用户资料
            try:
                data = json.loads(request.body.decode('utf-8'))
            except (json.JSONDecodeError, UnicodeDecodeError):
                return JsonResponse({
                    'status': 'error',
                    'message': '请求数据格式错误'
                }, status=400)
            
            # 更新通用字段
            if 'bio' in data:
                user.bio = data['bio']
            
            # 根据用户类型更新特定字段
            if user_type == 'admin' and user.is_admin:
                if 'name' in data and data['name'].strip():
                    user.name = data['name'].strip()
                if 'phone' in data:
                    user.phone = data['phone']
                if 'email' in data:
                    user.email = data['email']
                    
            elif user_type in ['employee', 'safety']:
                if 'name' in data and data['name'].strip():
                    user.name = data['name'].strip()
                if 'gender' in data:
                    user.gender = data['gender']
                if 'department' in data:
                    user.department = data['department']
                if 'position' in data:
                    user.position = data['position']
                if 'contact' in data:
                    user.contact = data['contact']
                if 'hire_date' in data and data['hire_date']:
                    try:
                        user.hire_date = datetime.strptime(data['hire_date'], '%Y-%m-%d').date()
                    except ValueError:
                        return JsonResponse({
                            'status': 'error',
                            'message': '入职日期格式错误，应为YYYY-MM-DD'
                        }, status=400)
                
                if user_type == 'safety' and user.is_safety_officer:
                    if 'license_number' in data:
                        user.license_number = data['license_number']
                    if 'management_scope' in data:
                        user.management_scope = data['management_scope']
            
            # 保存更新
            user.save()
            
            logger.info(f"用户资料更新成功: {user_type} {user_id}")
            
            return JsonResponse({
                'status': 'success',
                'message': '个人资料更新成功'
            })
        
    except Exception as e:
        logger.error(f"用户资料操作失败: {str(e)}", exc_info=True)
        return JsonResponse({
            'status': 'error',
            'message': f'操作失败：{str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["POST"])
def change_user_password(request, user_id):
    """
    修改用户密码（仅适用于管理员）
    
    Args:
        user_id: 管理员用户ID
    
    Returns:
        JsonResponse: 包含修改结果的JSON响应
    """
    try:
        data = json.loads(request.body.decode('utf-8'))
        
        # 验证必需字段
        required_fields = ['current_password', 'new_password']
        missing_fields = [field for field in required_fields if not data.get(field)]
        if missing_fields:
            return JsonResponse({
                'status': 'error',
                'message': f'缺少必需字段: {", ".join(missing_fields)}'
            }, status=400)
        
        # 验证密码长度
        if len(data['new_password']) < 6:
            return JsonResponse({
                'status': 'error',
                'message': '新密码长度至少需要6个字符'
            }, status=400)
        
        # 获取管理员用户
        try:
            user = Employee.objects.get(id=user_id, is_admin=True)
        except Employee.DoesNotExist:
            return JsonResponse({
                'status': 'error',
                'message': '管理员不存在'
            }, status=404)
        
        # 验证当前密码
        if not user.check_password(data['current_password']):
            return JsonResponse({
                'status': 'error',
                'message': '当前密码不正确'
            }, status=400)
        
        # 设置新密码
        user.set_password(data['new_password'])
        user.save()
        
        logger.info(f"管理员密码修改成功: {user_id}")
        
        return JsonResponse({
            'status': 'success',
            'message': '密码修改成功，请重新登录'
        })
        
    except json.JSONDecodeError:
        return JsonResponse({
            'status': 'error',
            'message': '请求数据格式错误'
        }, status=400)
    except Exception as e:
        logger.error(f"修改密码失败: {str(e)}", exc_info=True)
        return JsonResponse({
            'status': 'error',
            'message': f'修改密码失败：{str(e)}'
        }, status=500)
